import http from "../common/http";
//获取code
export const getCode = () => {
	const promise = new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin', //微信登录
			success: function(loginRes) {
				//如果返回了数据
				if (loginRes && loginRes.code) {
					//数据返回
					resolve(loginRes.code)
				} else {
					reject(loginRes)
				}
			}
		})
	}).catch(result => {
		uni.showToast({
			icon: 'none',
			title: result.errMsg || '获取code失败'
		})
	})
	return promise
}
//小程序登录
export const loginApi = (code) => {
	return http.post('/api/wechat/login', {
		code: code
	})
}
//封装登录
export const login = async () => {
	if (uni.getStorageSync('openid') && uni.getStorageSync('sessionKey')) {
		//存储
		uni.setStorageSync('openid', uni.getStorageSync('openid'))
		uni.setStorageSync('sessionKey', uni.getStorageSync('sessionKey'))
	} else {
		//获取code
		let result = await getCode()
		//登录
		const {
			data
		} = await loginApi(result)
		if (data) {
			//存储
			uni.setStorageSync('openid', data[0])
			uni.setStorageSync('sessionKey', data[1])
		}
	}
}
//新增地址
export const addAddressApi = (parm) => {
	return http.post("/api/wechat/address", parm)
}
//查询地址
export const getAddressListApi = (parm) => {
	return http.get("/api/wechat/address/list", parm)
}
//修改地址
export const editAddressApi = (parm) => {
	return http.post("/api/wechat/address/{addressId}", parm)
}
//查询默认地址
export const getAddressApi = (parm) => {
	return http.get("/api/wechat/address/default", parm)
}
//新增评论
export const addCommentApi = (parm) => {
	return http.post("/api/wechat/order/comment", parm)
}